package com.kfh.ybracelet.pay;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.PayListAdapter;
import com.kfh.ybracelet.alipay.PayResult;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.GoodsInfo;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.sim.IdentityActivity;
import com.kfh.ybracelet.sim.Status;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;

import java.util.Map;

/**
 * 充值页面
 * Created by Aaron on 16/9/7.
 */
public class PayActivity extends BaseActivity {

    //    private RecyclerView rv_money;
    private ListView lv_money;

    public String productId;
    private EditText et_tel;
    private IWXAPI wxapi;
    private LinearLayout ll_none;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pay);

        initWidget();

        getGoods();

//        GoodsInfo goodsInfo = new GoodsInfo();
//        List<GoodsInfo.ProductListEntity> productList = goodsInfo.getProductList();

        //注册到微信
        wxapi = WXAPIFactory.createWXAPI(this, null);
        wxapi.registerApp("wx6a271c2c414a2f13");//appid: wx6a271c2c414a2f13

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        RelativeLayout rl_alipay = (RelativeLayout) findViewById(R.id.rl_alipay);
        RelativeLayout rl_weixin = (RelativeLayout) findViewById(R.id.rl_weixin);

        ll_none = (LinearLayout) findViewById(R.id.ll_none);

        et_tel = (EditText) findViewById(R.id.et_tel);

        iv_left.setOnClickListener(this);
        rl_alipay.setOnClickListener(this);
        rl_weixin.setOnClickListener(this);
        tv_title.setText(getResources().getString(R.string.pay_charge));

        lv_money = (ListView) findViewById(R.id.lv_money);

//        rv_money = (RecyclerView) findViewById(R.id.rv_money);
//
//        rv_money.setHasFixedSize(true);
////        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
//        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(this);
//        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        rv_money.setLayoutManager(linearLayoutManager);
//        rv_money.setItemAnimator(new DefaultItemAnimator());
//        rv_money.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(this, 10)));
//
////        rv_money.addItemDecoration(new DividerItemDecoration(this,
////                DividerItemDecoration.VERTICAL_LIST));
    }


    private void getGoods() {

        try {
            JSONObject j = new JSONObject();
            j.put("token", sp.getString(Constant.TOKEN, ""));

            HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_PAY + Constant.PRODUCTLIST, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                @Override
                public void setOnSuccessListener(String str) {

                    GoodsInfo goodsInfo = JSONObject.parseObject(str, GoodsInfo.class);

                    if (goodsInfo.getProductList() == null || goodsInfo.getProductList().size() == 0) {
                        //数量为0 显示尽请期待页面
                        ll_none.setVisibility(View.VISIBLE);
                        return;
                    } else {
                        ll_none.setVisibility(View.GONE);
                    }

                    PayListAdapter chooseNewSimListAdapter = new PayListAdapter(PayActivity.this, 0x256, goodsInfo.getNewList(), goodsInfo.getProductList());
                    lv_money.setAdapter(chooseNewSimListAdapter);

                }
            }, null);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 请求服务器 发起支付
     *
     * @param productId
     * @param payStyle
     */
    public void pay(String productId, final String payStyle) {

        try {

            JSONObject info = new JSONObject();
            info.put("phoneNum", et_tel.getText().toString().trim());
            info.put("name", "");
            info.put("address", "");

            JSONObject j = new JSONObject();
            j.put("token", sp.getString(Constant.TOKEN, ""));
            j.put("productId", productId);
            j.put("type", payStyle);
            j.put("body", info.toJSONString());
//            j.put("body", info);
            j.put("spbill_create_ip", CommonUtils.getIpAddress(this));

//            LogUtil.e("tag", "IP 地址: " + getLocalIpAddress());
//            getIpAddress(this);
//            LogUtil.e("PayActivity", " ip 地址 : " + getIpAddress(this));

            HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_PAY + Constant.PAY, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
//            HttpUtil.setPostRequest("获取中...", this, "http://10.0.0.5:10008/yellow/" + Constant.PAY, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                @Override
                public void setOnSuccessListener(String str) {

                    try {

//                            String sign = result.getString("sign");

                        //发起支付
                        switch (payStyle) {

                            case Constant.PAY_STYLE_WEIXIN://微信支付

//                                LogUtil.e("payactivity", "======== 开始 微信支付 ========");

                                payWeiXin(str);

//                                LogUtil.e("payactivity", "======== 开始 微信结束 ========");

                                break;

                            case Constant.PAY_STYLE_ALIPAY://支付宝支付

                                org.json.JSONObject result = new org.json.JSONObject(str);

                                payAlipay(result.getString("sign"));

//                                if (result.getInt("code") == Constant.STATUS_SUCCESS) {
//
//                                    payAlipay(result.getString("sign"));
//                                } else if (result.getInt("code") == Constant.FA_TOKEN_TIMEOUT_ERROR) {//登录超时
//
//                                    loginOffTime();
//
//                                } else {
//                                    showToast(result.getString("code_msg"));
//                                }

                                break;
                        }

//                        GoodsInfo goodsInfo = JSONObject.parseObject(str, GoodsInfo.class);
//                        if (goodsInfo != null && goodsInfo.getProductList() != null) {
//
//                            ChooseMoneyAdapter chooseMoneyAdapter = new ChooseMoneyAdapter(PayActivity.this, goodsInfo.getProductList());
//                            rv_money.setAdapter(chooseMoneyAdapter);
//                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }, null);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 微信支付
     *
     * @param sign
     */
    private void payWeiXin(String sign) {

//        LogUtil.e("payactivity", " 解析服务器返回的数据 : " + sign);

        try {

            org.json.JSONObject result = new org.json.JSONObject(sign);

            String re = result.getString("re");

            org.json.JSONObject json = new org.json.JSONObject(re);

            PayReq req = new PayReq();
            req.appId = json.getString("appid");
            req.partnerId = json.getString("partnerid");
            req.prepayId = json.getString("prepayid");
            req.nonceStr = json.getString("noncestr");
            req.timeStamp = json.getString("timestamp");
            req.packageValue = json.getString("package");
            req.sign = json.getString("sign");
            req.extData = "app data";

            LogUtil.e("payactivity", " 开始发起微信支付");
            wxapi.sendReq(req);

        } catch (Exception e) {
            e.printStackTrace();
        }


//        WeixinResultBean payReq = JSONObject.parseObject(sign, WeixinResultBean.class);
//        LogUtil.e("payactivity", " 解析服务器返回的数据成功");
////        WeixinPayBean weixinPayBean = JSONObject.parseObject(sign, WeixinPayBean.class);
//        LogUtil.e("payactivity", " 开始发起微信支付");

//        List<Object> signParams = new LinkedList();
//        signParams.add(new BasicNameValuePair("appid", req.appId));
//        signParams.add(new BasicNameValuePair("appkey", app_wx_pay_key));
//        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
//        signParams.add(new BasicNameValuePair("package", req.packageValue));
//        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
//        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
//
//        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
//
//        req.sign = WeixinUtil.genSign(signParams);


//        PayReq payReq1 = payReq.getRe();
//        LogUtil.e("tag", "参数, appId:" + payReq1.appId +
//                ",\r\n nonceStr:" + payReq1.nonceStr +
//                ",\r\n packageValue:" + payReq1.packageValue +
//                ",\r\n partnerId:" + payReq1.partnerId +
//                ", \r\n prepayId:" + payReq1.prepayId +
//                ",\r\n sign:" + payReq1.sign +
//                ",\r\n timeStamp:" + payReq1.timeStamp);
//
//
//        wxapi.sendReq(payReq.getRe());
//        LogUtil.e("payactivity", " 开始发起微信支付成功");
    }

    /**
     * 支付宝支付
     *
     * @param orderInfo
     */
    private void payAlipay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.e("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private final String TAG = getClass().getSimpleName();

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功

                    LogUtil.e(TAG, "支付宝支付结果: " + resultInfo);

                    switch (resultStatus) {

                        case "9000":
                            showToast("支付成功");

                            Intent mIntent = new Intent(PayActivity.this, WXPayEntryActivity.class);
//                            mIntent.putExtra("alipayResult", resultInfo);
                            startActivity(mIntent);

                            break;
                        case "4000":
                            showToast("订单支付失败");
                            break;
                        case "5000":
                            showToast("重复请求");
                            break;
                        case "6001":
                            showToast("支付取消");
                            break;
                        case "6002":
                            showToast("网络连接出错");
                        default:
                            showToast("支付失败");
                            break;

                    }

//                    if (TextUtils.equals(resultStatus, "9000")) {
//                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//
//                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//                    } else {
//                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
//                    }

                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void widgetClick(View v) {

//        String pay_style;

        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;

            case R.id.rl_alipay://支付宝支付

                if (TextUtils.isEmpty(et_tel.getText().toString().trim())) {
                    showToast("请输入要充值的手机号");
                    return;
                }

                if (TextUtils.isEmpty(productId)) {
                    showToast("请选择充值类型");
                    return;
                }

//                pay_style = PAY_STYLE_ALIPAY;

                checkIsAuth(productId, Constant.PAY_STYLE_ALIPAY);

////                // 充值
//                pay(productId, PAY_STYLE_ALIPAY);

                break;

            case R.id.rl_weixin://微信支付

                if (TextUtils.isEmpty(et_tel.getText().toString().trim())) {
                    showToast("请输入要充值的手机号");
                    return;
                }

                if (TextUtils.isEmpty(productId)) {
                    showToast("请选择充值类型");
                    return;
                }
//                pay_style = PAY_STYLE_WEIXIN;

                checkIsAuth(productId, Constant.PAY_STYLE_WEIXIN);
//                pay(productId, PAY_STYLE_WEIXIN);

                break;

        }

    }

    /**
     * 检查手机号码是否实名认证过
     */
    private void checkIsAuth(final String productId, final String pay_style) {

        JSONObject param = new JSONObject();
        param.put("token", sp.getString(Constant.TOKEN, ""));
        param.put("phoneNum", et_tel.getText().toString().trim());

        HttpUtil.setPostRequest("", this, Constant.WEB_ROOT_PAY + Constant.CHECKPHONENUM,
                param.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {
                            org.json.JSONObject result = new org.json.JSONObject(str);

//                            if (result.getInt("code") == Constant.STATUS_SUCCESS) {

                            switch (result.getInt("check")) {
                                case Status.AUTH_NO_INFO://未提交过

                                    new AlertDialog.Builder(PayActivity.this)
//                                                .setTitle("提示")
                                            .setMessage("您未进行实名,请先实名认证")
                                            .setPositiveButton("认证", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                    Intent mIntent = new Intent(PayActivity.this, IdentityActivity.class);
                                                    startActivity(mIntent);
//                                                        finish();
                                                }
                                            }).setNegativeButton("取消", null).show();

                                    break;
                                case Status.AUTHING://审核中

                                    new AlertDialog.Builder(PayActivity.this)
//                                                .setTitle("提示")
                                            .setMessage("您的信息正在审核中,请等待审核结果")
                                            .setPositiveButton("确定", null)
                                            .setNegativeButton("取消", null).show();

                                    break;
                                case Status.AUTH_PASS://认证通过

                                    //  认证通过发起支付
                                    pay(productId, pay_style);

                                    break;
                                case Status.AUTH_REFUSE://认证驳回

                                    new AlertDialog.Builder(PayActivity.this)
                                            .setTitle(result.getString("msg"))
                                            .setMessage(result.getString("reply") + ",请重新认证")
                                            .setPositiveButton("认证", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                    Intent mIntent = new Intent(PayActivity.this, IdentityActivity.class);
                                                    startActivity(mIntent);
                                                    finish();
                                                }
                                            }).setNegativeButton("取消", null).show();

                                    break;

                            }

//                            } else {
//                                showToast(Constant.showErrorMsg(result.getInt("code"), getApplication()));
//                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());

    }

}
